package com.pattern.command.frame;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class CommandChain {
    // 保存回滚节点
    private final Stack<Command> undoCommands = new Stack<>();

    // 保存处理节点
    private final List<Command> commandList = new ArrayList<>();

    // 处理节点下标
    private int index = 0;

    private void undoCmds() {
        System.out.println("undo all commands --------------------------");
        while(!undoCommands.isEmpty()) {
            Command command = undoCommands.pop();
            boolean undoResult = command.undo();
            // 此处可根据undoResult做进一步的处理（例如失败重试3次，失败记录日志等）
        }
    }

    // 动态扩展处理节点
    public CommandChain addCommand(Command cmd) {
        commandList.add(cmd);
        return this;
    }

    // 递归遍历整个commandList链表
    public boolean executeCommands() {
        if (index == commandList.size()) {
            return true;
        }
        Command cmd = commandList.get(index);
        index++;
        if(cmd.execute()) {  // 此处可以设置重试机制
            undoCommands.push(cmd);
            return executeCommands();
        } else {
            undoCmds();
            return false;
        }
    }
}